<?php

namespace app\service\admin;

use app\service\article\ArticleModel;
use app\service\base\BaseLogic;

class AdminLogic extends BaseLogic
{
    const STATUS_NORMAL = 1;
    const STATUS_LOCK = 2;

    public function getList($username, $roleId, $limit)
    {
        $arrWhere = [];
        $username && $arrWhere['username'] = ['like', "%{$username}%"];
        $roleId && $arrWhere['role_id'] = $roleId;
        $arrData = (new AdminModel())->getPage($arrWhere, $limit);

        // 数据处理
        $arrRole = AdminRoleLogic::getInstance()->getAll();
        $arrRole = array_column($arrRole, 'name', 'id');
        $arrData['data'] = array_map(function ($arrVal) use ($arrRole) {
            $arrVal['role_name'] = $arrRole[$arrVal['role_id']] ?? '';
            return $arrVal;
        }, $arrData['data']);

        return $arrData;
    }

    public function check($username, $password)
    {
        $arrWhere = [];
        $arrWhere['username'] = $username;
        $arrWhere['password'] = $password;
        return (new AdminModel())->getRow($arrWhere);
    }

    public function add($username, $password, $rePassword, $realName, $mobile, $roleId)
    {
        if ($password != $rePassword) {
            return error('两次密码不一致');
        }
        $arrWhere = [];
        $arrWhere['username'] = $username;
        $exist = (new AdminModel())->getRow($arrWhere);
        if ($exist) {
            throw new \Exception('已存在相同名称');
        }

        return (new AdminModel())->add($username, $password, $roleId, $realName, $mobile, self::STATUS_NORMAL);
    }

    public function edit($id, $username, $password, $rePassword, $realName, $mobile, $roleId)
    {
        if (($password || $rePassword) && ($password != $rePassword)) {
            throw new \Exception('两次密码不一致');
        }
        $arrWhere = [];
        $arrWhere[] = ['id', '<>', $id];
        $arrWhere[] = ['username', '=', $username];
        $exist = (new AdminModel())->getRow($arrWhere);
        if ($exist) {
            throw new \Exception('已存在相同名称');
        }

        return (new AdminModel())->edit($id, $username, $password, $roleId, $realName, $mobile, self::STATUS_NORMAL);
    }

    public function getRowById($id)
    {
        $arrWhere = [];
        $arrWhere['id'] = $id;
        return (new AdminModel())->getRow($arrWhere);
    }

    public function del($id)
    {
        if (empty($id)) {
            throw new \Exception('更新参数错误');
        }
        return (new AdminModel())->delById($id);
    }

    public function modifyPassword($id, $password)
    {
        (new AdminModel())->modifyPassword($id, $password);
    }

    public function getListByIds($arrIds)
    {
        $arrWhere = [];
        $arrWhere[] = ['id', 'in', $arrIds];
        return (new AdminModel())->getList($arrWhere, 'id, real_name');
    }
}